<?php

declare(strict_types=1);

namespace App\Model\CommodityModel;

use App\Model\BaseModel\BaseCommodityModel;
use Hyperf\DbConnection\Db;
use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Service\SearchService\Index\ShopCommodityIndex;
use Hyperf\DbConnection\Pool\DbPool;
class Classifyinfo extends BaseCommodityModel
{
    public $table = 'classifyinfo_s2b';
    
    //指定字段展示类型
    protected $casts = [
        'id'    => 'string',
        'pid'   => 'string'
    ];
    
    /**
     * 获取分类树
     */
    public function getClassLists() {
        return self::query()
        ->where([
            ['IsDeleted','=',0]
        ])
        ->select([
             Db::raw('CONCAT(ID,"") as class_id'),
             Db::raw('ClassificationName as class_name'),
             Db::raw('CONCAT(IFNULL(ParentID,0),"") as class_pid'),
             Db::raw('Level as class_level'),
             Db::raw('IFNULL(Image,"") as class_image'),
        ])
        ->get()
        ->toArray();
    }
    
    /**
     * 获取分类树
     */
    public function getClassByBids( $ids = [] ) {
        return $this
        ->select([
            Db::raw('CONCAT(ID,"") as id'),
            Db::raw('ClassificationName as class_name'),
            Db::raw('CONCAT(IFNULL(ParentID,0),"") as pid'),
            Db::raw('Level as level'),
            Db::raw('Image'),
        ])
        ->where('IsNotShow','=',0)
        ->whereIn('ID',$ids)
        ->get()
        ->toArray();
    }
    
    /**
     * 获取首页分类菜单
     */
    public function getClassTree() {
        
        $cacheKey = "WEB_CLASS_TREE";
        $redis = BaseService::instance()->getRedisObj();
        $redis->select(BaseService::rdb_num);
        $lists = $redis->get($cacheKey);
        if( !empty($lists) ) {
            $lists = json_decode($lists,true);
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'classList' => $lists
            ]);
        }
        
        $list = self::query()
        ->where([
            ['IsDeleted','=',0]
        ])
        ->select([
             Db::raw('CONCAT(ID,"") as id'),
             Db::raw('ClassificationName as class_name'),
             Db::raw('CONCAT(IFNULL(ParentID,0),"") as pid'),
             Db::raw('Level'),
        ])
        ->get()
        ->toArray();
        
        $tree = tree($list, 0, 'id', 'pid');
        //更新查询结果到缓存
        $redis->set($cacheKey,json_encode($tree),BaseService::CACHE_TIME);
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'classList' => $tree
        ]);
    }
    
    /**
     * 获取优选商品分类树
     */
    public function getClassTreeFromMicoServicePriotity()
    {
        $res = ShopCommodityIndex::instance()->getClassList();
        if( !isset($res['aggregations']) ) {
            return Normal::returnCode(Normal::SUC,"暂无数据",$res);
        }
        
        $aggregations   = $res['aggregations'];
        $f_class_ids    = array_column($aggregations['f_class_id']['buckets'],'key');
        $s_class_ids    = array_column($aggregations['s_class_id']['buckets'],'key');
        $t_class_ids    = array_column($aggregations['t_class_id']['buckets'],'key');
        $allClassIds    = array_merge($f_class_ids,$s_class_ids,$t_class_ids);
        if( empty($allClassIds) ) {
            return Normal::returnCode(Normal::SUC,"暂无数据");
        }
        
        /*
        $table  = CommodityOptimizationBbc::instance()->getTableByBuID(0)->getTable();
        $list   = CommodityOptimizationBbc::instance()->getTableByBuID(0)
        ->from($table." as cop")
        ->select([
            Db::raw('DISTINCT CONCAT(com.ThirdClassificationID) as ThirdClassificationID'),
            Db::raw("CONCAT(com.SecondClassificationID) as SecondClassificationID"),
            Db::raw("CONCAT(com.FirstClassificationID) as FirstClassificationID"),
        ])
        ->join("commodityarchives_s2b as com","com.ID","=","cop.SkuID")
        ->where("cop.IsInit",1)
        ->get()
        ->toArray();
        
        if( empty($list) ) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'classList' => []
            ]);
        }
        
        $ThirdClassificationID  = array_unique(array_column($list,'ThirdClassificationID'));
        $SecondClassificationID = array_unique(array_column($list,'SecondClassificationID'));
        $FirstClassificationID  = array_unique(array_column($list,'FirstClassificationID'));
        $allClassIds = array_merge($ThirdClassificationID,$SecondClassificationID,$FirstClassificationID);
        */
        $list = Classifyinfo::instance()->getClassByBids($allClassIds);
        $tree = tree($list,0, 'id', 'pid');
        //更新查询结果到缓存
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'classList' => $tree
        ]);
    }
    
    /**
     * BBC专用
     * 查询二级分类开始
     */
    public function queryClassList()
    {
        $list = $this->select([
            Db::raw("ID AS id"),
            Db::raw("ParentID AS pid"),
            Db::raw("Image as imageUrl"),
            Db::raw("ClassificationName as name"),
            Db::raw("Level as level"),
        ])
        ->where('Level','>',0)
        ->where('IsDeleted',0)
        ->get()
        ->toArray();
        $list = array_map(function( & $value){
            if( $value['imageUrl'] ) {
                $value['imageUrls'] = [$value['imageUrl']];                
            } else {
                $value['imageUrls'] = [];
            }
            return $value;
        },$list);
        
        $listTree = tree($list,0,'id','pid');
        $ListNewMap = [];
        foreach ($listTree as $key => $value ) 
        {
            if( !empty($value['list']) ) 
            {
                foreach ($value['list'] as $child )
                {
                    $ListNewMap[] = $child;
                }
            }
            unset($value);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$ListNewMap);
    }
    
    /**
     * BBC
     * 查询分类名称
     */
    public function queryClassInfo( $body = [] )
    {
        if( empty($body) ) {
            return Normal::returnCode(Normal::FAIL,"查询条件不能为空");
        }
        
        $current = current($body);
        if( is_string($current) ) {
            return Normal::returnCode(Normal::FAIL,"当前查询数据必须二维数组");
        }
        
        if( empty($current['name']) ) {
            return Normal::returnCode(Normal::FAIL,"查询name不能为空");
        }
        
        if( empty($current['level']) ) {
            return Normal::returnCode(Normal::FAIL,"查询level不能为空");
        }
        
        $row = $this->select([
            Db::raw("ID AS id"),
            Db::raw("ParentID AS pid"),
            Db::raw("Image as imageUrl"),
            Db::raw("ClassificationName as name"),
            Db::raw("Level as level"),
        ])
        ->where('ClassificationName','=',$current['name'])
        ->where('Level','=',$current['level'])
        ->first();
        
        if( $row ) {
            $row = $row->toArray();
            if( $row['imageUrl'] ) {
                $row['imageUrls'] = [$row['imageUrl']];
            } else {
                $row['imageUrls'] = [];
            }
            $row['children'] = [];
        } else {
            $row = [];
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",$row);
    }
}